package com.lagou.java.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class RedisSession {

    private static RedisUtil redisUtil ;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        RedisSession.redisUtil = redisUtil;
    }

    // encrypt SALT
    private static final String SALT = "U70tIpEzGrjiUw5qnsNR4g==";
    private static final String SESSION_PREFIX = "Session-";

    private RedisSession (){}

    public static class SessionData {

        public SessionData() {}

        public SessionData(String sessionId, String userName) {
            this.sessionId = sessionId;
            UserName = userName;
        }

        private String sessionId;
        private String UserName;

        public String getSessionId() {
            return sessionId;
        }

        public void setSessionId(String sessionId) {
            this.sessionId = sessionId;
        }

        public String getUserName() {
            return UserName;
        }

        public void setUserName(String userName) {
            UserName = userName;
        }

        @Override
        public String toString() {
            return "SessionData{" +
                    "sessionId='" + sessionId + '\'' +
                    ", UserName='" + UserName + '\'' +
                    '}';
        }
    }

    private static  RedisSession instant = new RedisSession();

    public static RedisSession getInstance () {
        return instant;
    }

    public static RedisUtil getRedisUtil() {
        return redisUtil;
    }

    /**
     *  生成 session 信息，
     */
    public static String newSession (String username, HttpServletResponse response, int expireMunites) throws Exception {
        String token = EncryptUtil.encrypt(SALT, SALT, username);
        // 将数据存入 cookie
        addCookie(response, "token", token, expireMunites * 60);
        // 生成session信息
        String redisSessionKey = SESSION_PREFIX + username;
        String sessionId = UUID.randomUUID().toString();
        String sessionData = JSON.toJSONString(new SessionData(username, sessionId));
        // 将 session 数据存入 Redis
        getRedisUtil().setWithExpir(redisSessionKey, sessionData, expireMunites);
        return sessionId;
    }

    /**
     * 核验 session 信息
     * @return
     */
    public static String checkSessionInfo (HttpServletRequest request, HttpServletResponse response, int expireMunites) throws Exception {
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                String username = EncryptUtil.decrypt(SALT, SALT, cookie.getValue());
                String sessionInfo = getRedisUtil().get(SESSION_PREFIX + username);
                if( sessionInfo != null && !sessionInfo.trim().equals("")) {
                    // 刷新 cookie 信息过期时间
                    addCookie(response, "token", cookie.getValue(), expireMunites * 60);
                    // 从 Redis 获取 session 信息
                    SessionData sessionData = JSON.parseObject(sessionInfo, SessionData.class);
                    sessionId = sessionData.getSessionId();
                }
            }
        }
        return sessionId;
    }

    /**
     * 设置cookie
     * @param response
     * @param name  cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期  以秒为单位
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge){
        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        if(maxAge>0)  cookie.setMaxAge(maxAge);
        response.addCookie(cookie);

    }

}
